//
//  PYLineLayout.m
//  Line_fall
//
//  Created by zpy on 15/12/2.
//  Copyright © 2015年 zpy. All rights reserved.
//

#import "PYLineLayout.h"

@implementation PYLineLayout
/**
 *  初始化布局
 */
-(instancetype)init{

    if (self = [super init]) {
        
    }
    return self;
}
/**
*  准备布局
*/
-(void)prepareLayout{
    [super prepareLayout];
// 水平滚动
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // cell 的尺寸
    CGFloat itemWH = self.collectionView.frame.size.height * 0.6;
    self.itemSize = CGSizeMake(itemWH, itemWH);
    // 内边距
    CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;
    self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);
    
}
/**
 *  返回UICollectionView上所有元素的布局属性
 */
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
//调用父类方法拿到默认的布局属性
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    // 获得collectionView 中点   x 的值
    CGFloat centerX = self.collectionView.frame.size.width * 0.5 + self.collectionView.contentOffset.x;
    for (UICollectionViewLayoutAttributes *attrs in array) {
        CGFloat delta = ABS(attrs.center.x - centerX);
        // 根据距离计算缩放比例,离得cell离中心线越远,应该越小
        CGFloat scale = 1 - delta / (self.collectionView.frame.size.width + attrs.size.width);
        attrs.transform = CGAffineTransformMakeScale(scale, scale);
    }
    return array;
}
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{

    return YES;
}
/**
 *  targetContentOffset：CollectionView最终的偏移量
 *  proposedContentOffset：CollectionView预期的偏移量
 */
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
    // 计算最终的可见范围
    CGRect rect;
    rect.origin = proposedContentOffset;
    rect.size = self.collectionView.frame.size;
    
    // 取得cell的布局属性
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    
    // 计算CollectionView中线的x值
    CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;
    
    CGFloat minDelta = MAXFLOAT;
    for (UICollectionViewLayoutAttributes *attrs in array) {
        CGFloat delta = attrs.center.x - centerX;
        
        if (ABS(delta) <= ABS(minDelta)) {
            minDelta = delta;
        }
    }
    
    return CGPointMake(proposedContentOffset.x + minDelta, proposedContentOffset.y);
}
@end
